<?php
namespace mybackend\controllers;

use Yii;
use common\services\myhtsq\RevenueService;
use common\services\myhtsq\ContractService;
use common\error\ErrorCode;
use common\entities\myhtsq\ActionCode;
use common\models\myhtsq\RevenueModel;
use common\models\myhtsq\RevenueRecognitionModel;
use yii\filters\AccessControl;
use common\services\myhtsq\ErpInterfaceService;
use common\services\myhtsq\LogService;
use common\models\myhtsq\ContractApiLogModel;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ErpUserRepository;


/**
 * Description of RevenueController
 * 收入控制器
 * @author zhoud01
 */
class RevenueController extends BaseController {

    private $_revenueService;
    private $_contractService;
    private $_logService;

    public function __construct($id, $module, RevenueService $revenueService, ContractService $contractService,LogService $logService,$config = array()) {
        $this->_revenueService = $revenueService;
        $this->_contractService = $contractService;
        $this->_logService = $logService;
        parent::__construct($id, $module, $config);
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['Revenue-expired-remind'],
                        'allow' => true,
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    protected function roleAuthRules(){
        return [
            'actions'=>['DelRevenueByRevenueId','GetRevenueInfo','SaveRevenue','GetRevenueListByPage','UpdateRecognitionByRevenueId'],
            'rules'=>[
                        [
                        'allow'=>true,
                        'actionCodeMaps'=>[
                            'GetRevenueInfo'=>ActionCode::REVENUE_VIEW,
                            'GetRevenueListByPage'=>ActionCode::REVENUE_VIEW,
                            'SaveRevenue'=>ActionCode::REVENUE_MOD,
                            'DelRevenueByRevenueId'=>ActionCode::REVENUE_MOD,//删除收入
                            'UpdateRecognitionByRevenueId'=>ActionCode::REVENUE_MOD,//修改结转
                            ]
                        ]
                    ]
                ];
    }

    /**
     * 收入管理模块：获取收入列表信息，支持分页
     */
    public function actionGetRevenueListByPage()
    {
        $revenueModel = new RevenueModel(['scenario' => 'getRevenueListByPage']);
        if ($revenueModel->paramsGetValidate()) {
            $data = $this->_revenueService->getRevenueListByPage($revenueModel);
            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data
            ]);
        } else {
            Yii::error($revenueModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueModel->getErrCode(),
                'errMsg' => $revenueModel->getErrMsg(),
            ]);
        }
    }


    /**
     * 收入管理模块: 收入确认
     */
    public function actionRevenueRecognition()
    {
        set_time_limit(0);
        ini_set('memory_limit', '2024M');

        $userGuid = \Yii::$app->user->identity->userguid;

        $prefix = 'revenueRecognition';
        $cachekey = $prefix.$userGuid;
        //\Yii::$app->cache->delete($cachekey);die;//清除key

        $get = \Yii::$app->cache->get($cachekey);
        if(!empty($get)){
            $params = [
                'data'=>'收入结转中等待邮件发送',//初次导出Excle
                'retCode'=>0,
            ];

            echo json_encode($params);//开始导出
        }else {
            \Yii::$app->cache->set($cachekey,'waiting',36000);
            $params = [
                'data'=>'收入结转中等待邮件发送,请不要重复点击!',//初次导出Excle
                'retCode'=>0,
            ];
            echo json_encode($params);//开始导出
        }
        fastcgi_finish_request();
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'saveRevenueRecognition']);
        if ($revenueRecognitionModel->paramsPostValidate()) {

            $params = $revenueRecognitionModel->getAttributes();

            $revenueList = $this->_contractService->getRevenueInfoByRecognitionTime($params['recognition_type']);//不传时间全量收入获取

//            foreach ($revenueList as $k=>$v){
//
//                $list = $this->_revenueService->getRecognitionList($v['revenue_id']);//有可能存在收入关闭装未null的记录收入不确定因此待确认收入依然有值
//                if(count($list)>1||in_array($v['close_status'],[2,3,4])){//收入关闭的不进行结转
//                    unset($revenueList[$k]);
//                }
//
//                if(($v['revenue_id'] !== $params['revenue_id'] && !empty($params['revenue_id']))||in_array($v['close_status'],[2,3,4])){//单条结转 收入关闭的不进行结转
//                    unset($revenueList[$k]);
//                }
//
//            }

            $data = null;
            $msg = '';
            if($params['recognition_type'] === 'date'){
                //按照租期确认 租用服务
                $data['date'] = $this->_revenueService->revenueRecognitionByDate($revenueList);
                $msg .=  '租期确认'.'成功:'.$data['date']['success'].'失败:'.$data['date']['fail'];
            }else if($params['recognition_type'] === 'disposable'){
                //一次性确认 增值服务
                $data['disposable'] = $this->_revenueService->revenueRecognitionByDisposable($revenueList);
                $msg .= '一次性确认'.'成功:'.$data['disposable']['success'].'失败:'.$data['disposable']['fail'];
            }else if($params['recognition_type'] === 'ad'){
                //广告
                $data['ad'] = $this->_revenueService->revenueRecognitionByAd($revenueList);
                $msg .= '广告'.'成功:'.$data['ad']['success'].'失败:'.$data['ad']['fail'];
            }else if($params['recognition_type'] === 'all'){
//                //按照租期确认 租用服务
//                $data['date'] = $this->_revenueService->revenueRecognitionByDate($revenueList);
//                //一次性确认 增值服务
//                $data['disposable'] = $this->_revenueService->revenueRecognitionByDisposable($revenueList);
//                //广告
//                $data['ad'] = $this->_revenueService->revenueRecognitionByAd($revenueList);
                //全部
                try{
                    $this->_revenueService->revenueRecognitionAll($revenueList);
                }catch (\Exception $e){
                    var_dump($e->getMessage());
                }
                $msg .= '全部数据转结完毕';
            }

            //获取最新结转人
            $recentRecognitionUser = $this->_revenueService->getRecentRecognitionUser();
            $data['user'] = $recentRecognitionUser['recognition_by'];
            $data['time'] = $recentRecognitionUser['recognition_date'];

            $user = ErpUserRepository::getUserById($userGuid);
            $this->_revenueService->sendMail($user['Email'],'结转结果',$msg);

            \Yii::$app->cache->delete($cachekey);//清除key

            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }
    }

    /**
     * 收入管理模块: 查询确认收入&收入&合同
     * 收入结转表
     */
    public function actionGetRecognitionRevenueContractListByDate()
    {
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'selectRevenueRecognition']);
        $recognitionList = $this->getParam('recognitionEnd', 'post'); //收入信息

        if ($revenueRecognitionModel->paramsPostValidate()) {
            $revenueRecognitionModel->recognition_end = $recognitionList;
            $data = $this->_revenueService->getRecognitionRevenueContractPageByDate($revenueRecognitionModel);
            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }

    }

    /**
     * 收入管理模块: 查询收入&回款&应收
     */
    public function actionGetRevenueReceivablePaymentListByDate()
    {
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'selectRevenueReceivablePayment']);
        $recognitionList = $this->getParam('recognitionEnd', 'post'); //收入信息
        if ($revenueRecognitionModel->paramsPostValidate()) {
            $revenueRecognitionModel->recognition_end = $recognitionList;
            $data = $this->_revenueService->getRevenueReceivablePaymentListByDate($revenueRecognitionModel);
            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }

    }

    /**
     * 收入管理模块: 结转期间设置
     */
    public function actionSetRecognitionDate()
    {
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'saveRevenueRecognitionDate']);
        if ($revenueRecognitionModel->paramsPostValidate()) {
            #是否需要校验某种情况不可新增结转期
            $data = $this->_revenueService->setRecognitionDate($revenueRecognitionModel);
            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => (bool)$data
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }

    }

    /**
     * 收入管理模块: 查询当期结转期间
     */
    public function actionGetRecognitionDate()
    {
        $data = $this->_revenueService->getRecognitionDateNew();
        return $this->json([
            'retCode' => ErrorCode::SUCCESS,
            'data' => $data
        ]);

    }


    /**
     * 收入管理模块: 获取所结转期列表
     */
    public function actionGetRecognitionListDate()
    {
        $data = $this->_revenueService->getRecognitionListDate();
        return $this->json([
            'retCode' => ErrorCode::SUCCESS,
            'data' => $data
        ]);

    }

    /**
     * 收入管理模块: 最新结转人查询
     */
    public function actionGetRecentRecognitionUser()
    {
        $data = $this->_revenueService->getRecentRecognitionUser();
        return $this->json([
            'retCode' => ErrorCode::SUCCESS,
            'data' => $data
        ]);

    }

    /**
     * 收入管理模块: 根据收入id获取收结转信息
     */
    public function actionGetRevenueRecognitionListByRevenueId()
    {
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'selectRecognitionByRevenueId']);
        if ($revenueRecognitionModel->paramsGetValidate()) {
            $params = $revenueRecognitionModel->getAttributes();
            $data = $this->_revenueService->getRecognitionLastUnionThisIssueByRevenueId($params['revenue_id']);
            //需要包含所有 last_issue_total_recognition_amount  this_issue_total_recognition_amount
            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }

    }


    private function revenueCloseByRecognitionId($recognitionId){

        $recognition = $this->_revenueService->getRecognitionByRecognitionId($recognitionId);
        $revenue = $this->_contractService->getContractRevenueByRevenueId($recognition->revenue_id,$recognition->contract_id);
        $revenueAmount = (float)$revenue['revenueList'][0]['amount'];//收入总金额
        $totalRecognitionAmount = $revenue['revenueList'][0]['total_recognition_amount'];//累计确认金额

        $unrecognizedBadDebtAmount = $revenue['revenueList'][0]['unrecognized_bad_debt_amount'];//未确认坏账金额
        $recognizedBadDebtAmount = $revenue['revenueList'][0]['recognized_bad_debt_amount'];//已确认坏账金额
        $kingdeeBadDebtAmount = $revenue['revenueList'][0]['kingdee_bad_debt_amount'];//金蝶坏账金额

        $totalBadDebtAmount = (float)$unrecognizedBadDebtAmount + (float)$recognizedBadDebtAmount + (float)$kingdeeBadDebtAmount;
        $totalAmount = (float)$totalRecognitionAmount + (float)$totalBadDebtAmount;

        if($revenueAmount === $totalAmount){//if 收入总金额=当前累计收入+坏账金额 关闭 else 反关闭
            $this->_revenueService->updateCloseStatusRevenueByRevenueId($recognition['revenue_id'],3);
        }else{
            $this->_revenueService->updateCloseStatusRevenueByRevenueId($recognition['revenue_id'],1);
        }
    }

    /**
     * 收入管理模块: 根据收入id修改结转记录
     */
    public function actionUpdateRecognitionByRevenueId()
    {
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'updateRecognitionByRevenueId']);
        if ($revenueRecognitionModel->paramsPostValidate()) {

            //修改结转记录
            $data = $this->_revenueService->updateRevenueRecognition($revenueRecognitionModel);

            //if 收入总金额=当前累计收入+坏账金额  关闭 else 反关闭
            self::revenueCloseByRecognitionId($revenueRecognitionModel->recognition_id);

            $contractApiLogModel = new contractApiLogModel();
            $contractApiLogModel->log_type = 1;
            $contractApiLogModel->call_line = __LINE__;
            $contractApiLogModel->call_method = __METHOD__;
            $contractApiLogModel->call_parametes =json_encode([$revenueRecognitionModel->recognition_id,$revenueRecognitionModel->recognition_amount],JSON_UNESCAPED_UNICODE);
            $contractApiLogModel->return_data = json_encode($data,JSON_UNESCAPED_UNICODE);
            $contractApiLogModel->return_code = $this->_revenueService->getErrCode();
            $contractApiLogModel->error_msg = $this->_revenueService->getErrMsg();
            $contractApiLogModel->call_user = isset(\Yii::$app->user->identity->userguid) ? \Yii::$app->user->identity->userguid : '';
            $contractApiLogModel->maintain_remark = '根据收入id修改结转记录';
            $this->_logService->addContractApiLogRecord($contractApiLogModel);

            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }

    }

    /**
     * 收入管理模块: 删除收入
     */
    public function actionDelRevenueByRevenueId()
    {
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'delRevenueByRevenueId']);
        if ($revenueRecognitionModel->paramsPostValidate()) {

            $params = $revenueRecognitionModel->getAttributes();

            $data = $this->_revenueService->getRevenueRecognitionListByRevenueId($params['revenue_id']);

            if(!empty($data)){
                Yii::error($revenueRecognitionModel->getLogMsg());
                return $this->json([
                    'data' => $data,
                    'retCode' => -1,
                    'errMsg' => '如果该收入项有结转记录，不能删除',
                ]);
            }

            $userGuid = \Yii::$app->user->identity->userguid;

            libxml_disable_entity_loader(false);
            /** @var ErpInterfaceService $erpInterfaceService */
            $erpInterfaceService = \Yii::createObject(ErpInterfaceService::className());
            $revenueInfo = $this->_revenueService->getRevenueByRevenueId($params['revenue_id']);
            $revenueInfo['amount'] = 0;
            $contractManage = ContractManageRepository::getContractManageModelByContractId($revenueInfo['contract_id']);
            $contractManage->contract_property_id;
            //明源签约-直属 明源签约-联营 才调用接口
            if(in_array($contractManage->contract_property_id,['54f8a2b7-fce7-11e4-bed8-00155d02c832','7f828b1b-fce8-11e4-bed8-00155d02c832'])){
                $api = $erpInterfaceService->saveRevenue($revenueInfo);
            }
            $api = empty($api)?'非明源合同':$api;
            $parameter = $erpInterfaceService->parameterToJson($revenueInfo);

            $contractApiLogModel = new contractApiLogModel();
            $contractApiLogModel->log_type = 2;
            $contractApiLogModel->call_line = __LINE__;
            $contractApiLogModel->call_method = __METHOD__;
            $contractApiLogModel->call_parametes =json_encode($parameter,JSON_UNESCAPED_UNICODE);
            $contractApiLogModel->return_data = json_encode($api,JSON_UNESCAPED_UNICODE);
            $contractApiLogModel->return_code = $erpInterfaceService->getErrCode();
            $contractApiLogModel->error_msg = $erpInterfaceService->getErrMsg();
            $contractApiLogModel->call_user = empty($userGuid)?'0000-000-0000':$userGuid;
            $contractApiLogModel->maintain_remark = '删除收入';

            $this->_logService->addContractApiLogRecord($contractApiLogModel);
            $data = $this->_revenueService->delRevenueByRevenueId($params['revenue_id']);

            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data,
                'Msg' => $api,
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }

    }

    /**
     * 收入管理模块: 导出收入
     */
    public function actionExportRevenue()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'exportRevenue']);

        if ($revenueRecognitionModel->paramsGetValidate()) {
            $data = $this->_revenueService->exportRevenue($revenueRecognitionModel);
            return $this->json([
                'retCode' => ErrorCode::SUCCESS,
                'data' => $data
            ]);
        } else {
            Yii::error($revenueRecognitionModel->getLogMsg());
            return $this->json([
                'retCode' => $revenueRecognitionModel->getErrCode(),
                'errMsg' => $revenueRecognitionModel->getErrMsg(),
            ]);
        }

    }

}
